<template>
  <ekDialog
    v-model="ekVisiable"
    :title="title"
    @submit="handleSubmit"
    :hideBtn="disabled"
  >
    <div class="ek-form" v-loading="loading">
      <el-form
        :model="form"
        :rules="rules"
        label-width="160px"
        ref="formRef"
        :disabled="disabled"
        v-if="!loading"
      >
        <el-form-item   label="轮播图" prop="banner_image">
          <div  class="avatar-uploader">

             <el-upload
              v-model:file-list="fileList"
              :action="$uploadUrl"
              list-type="picture-card"
              :limit="1"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
               :headers="{
                Authorization: getToken()
              }"
            >
              <i class="icon iconfont icon-increase avatar-uploader-icon"></i>
            </el-upload>

          <el-image-viewer
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :url-list="[$imageBaseUrl+ form.banner_image]"
            :initial-index="0"
            :infinite="true"
            fit="cover"
            @close="handleClose"
            v-if="imageVisiable"
          ></el-image-viewer>
                  
    
          </div>
          </el-form-item>
          <el-form-item prop="banner_type" label="轮播图类型">
            <ekRadio
              v-model="form.banner_type"
              :options="typeOptions"
            />
        </el-form-item>
         <el-form-item prop="banner_position" label="所属菜单">
           <ekRadio
              v-model="form.banner_position"
              :options="positionOptions"
            />
        </el-form-item>
        <el-form-item label="标题">
            <el-input v-model="form.banner_title" placeholder="请输入标题"></el-input>
        </el-form-item>
       
        <el-form-item label="排序" prop="sort">
            <el-input type="number" v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="链接" v-if="form.banner_type == 'jump' || form.banner_type == 'open'">
            <el-input v-model="form.banner_page" placeholder="请输入小程序链接或者外部链接"></el-input>
        </el-form-item>
        
      </el-form>
    </div>
  </ekDialog>
</template>

<script setup>
import {
  watch,
  getCurrentInstance,
  computed,
  reactive,
  ref,
  defineEmits,
  onMounted,
} from "vue";
import { apis } from "../data.js";
import ekDrawer from "@/components/business/ekDrawer/index.vue";
import ekDialog from "@/components/business/ekDialog/index.vue";
import ekInput from "@/components/form/ekInput/index.vue";
import ekSelect from "@/components/form/ekSelect/index.vue";
import ekTip from "@/components/business/ekTip/index.vue";
import ekRadio from "@/components/form/ekRadio/index.vue";

import { objectAssignment } from "@/utils/common.js";
import { getDimensionByCode } from "@/utils/sys.js";
import { getToken } from '@/utils/sys';
const props = defineProps({
  // 显示隐藏
  visiable: {
    type: Boolean,
    default: false,
  },
  rowId: {
    type: [String, Number],
    default: "",
  },
  title: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
const { $storage, $http, $ekLoading, $ekMessage, $imageBaseUrl,$uploadUrl } = globalProperties;

const emit = defineEmits(["update:visiable", "submit"]);
const fileList = ref([])
const imageVisiable = ref(false);
const handlePictureCardPreview = () => {
  imageVisiable.value = true;
}
const handleClose = () => {
  imageVisiable.value = false;
}
// 超出上传数限制
const handleExceed =(files, uploadFiles) =>{
  $ekMessage.warning("超出文件上传数限制");
}
const handleRemove = ()=> {
  form.value.banner_image = ''
}
// 文件上传成功时的钩
const handleSuccess = (response, uploadFile, uploadFiles) =>{
  if(response.status == 'success'){
    form.value.banner_image = response.data.path;
  }
  
}

// 是否显示
const ekVisiable = computed({
  get() {
    return props.visiable;
  },
  set(value) {
    emit("update:visiable", value);
  },
});

function handleSubmit(done) {
  let url = props.rowId ? apis.edit : apis.add;
  formRef.value.validate((valid) => {
    if (valid) {
      $http
        .request({
          url: url,
          method: props.rowId ? "PUT" : "POST",
          data: {
            ...form.value,
          },
        })
        .then((res) => {
          $ekMessage.success(res.message);
          emit("submit", done);
        })
        .catch((err) => {});
    }
  });
}
const loading = ref(false);
let formRef = ref(null);
let form = ref(null);
let rules = reactive({
  banner_image: [{ required: true, message: "请输入轮播图", trigger: "blur" }],
  banner_type: [{ required: true, message: "请选择轮播图类型", trigger: "blur" }],
});
const detail = ref({
  role_state_dim_text: "",
});
const initForm = () => {
  form.value = {
    banner_image: "",
    banner_type: "normal",
    banner_title:"",
    banner_page: "",
    banner_position:"1",
    sort:"",
    id: props.rowId,
  };
};
// 初始化表单
async function init() {
  loading.value = true;
  // 详情或者编辑
  if (props.rowId) {
    $http
      .get(apis.detail, {
        params: {
          id: props.rowId,
        },
      })
      .then((res) => {
        if (Object.keys(res.data).length) {
          detail.value = {
            ...detail.value,
            ...res.data,
          };
          fileList.value = [
            {
              name: '',
              url: $imageBaseUrl  + res.data.banner_image,
            },
          ]
          objectAssignment(form.value, res.data);
        }
        loading.value = false;
      });
  } else {
    loading.value = false;
  }
}
 
const positionOptions = [{
  label:'首页',
  value:'1'
},{
  label:'计费查询',
  value:'2'
},{
  label:'包裹查询',
  value:'3'
}]
watch(
  () => props.visiable,
  (val) => {
    if (val) {
      fileList.value = []
      initForm();
      init();
    }
  }
);
const typeOptions = ref([])
onMounted(async () => {
    typeOptions.value = await getDimensionByCode("DIM_BANNER_TYPE");
});
</script>

<style scoped lang="scss">
:deep(.avatar-uploader) {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    
  }
}

</style>
